package com.h2cloud.JUCTest.notifyTest;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Package: com.h2cloud.JUCTest.notifyTest
 * @ClassName: ProductorConsumerDmoe3
 * @Author: h2cloud
 * @CreateTime: 2021/10/25 4:11 下午
 * @Description:
 */
public class ProductorConsumerDmoe3 {

    private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(15);
        for (int i = 0; i < 5; i++) {
            service.submit(new Productor(queue));
        }
        // for (int i = 0; i < 10; i++) {
        //     service.submit(new Consumer(queue));
        // }
    }

    static class Productor implements Runnable {
        private BlockingQueue queue;

        public Productor(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Random random = new Random();
                    int i = random.nextInt();
                    queue.put(i);
                    System.out.println("生产者" + Thread.currentThread().getName() + "生产数据" + i);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {
        private BlockingQueue queue;

        public Consumer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Integer element = (Integer) queue.take();
                    System.out.println("消费者" + Thread.currentThread().getName() + "正在消费数据" + element);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

